/* jQuery-based Popup logic */
(function () {
  // Helpers
  const fmtTime = (t) => {
    try {
      const d = new Date(t);
      const pad = (n) => (n < 10 ? "0" + n : "" + n);
      return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
    } catch { return ""; }
  };
  function bg(msg) {
    return new Promise((resolve) => {
      try {
        chrome.runtime.sendMessage(msg, (resp) => resolve(resp));
      } catch (e) {
        resolve({ ok: false, error: e?.message || "sendMessage failed" });
      }
    });
  }
  const api = {
    getState: () => bg({ type: "getState" }),
    setEnabled: (enabled) => bg({ type: "setEnabled", enabled }),
    getLogs: () => bg({ type: "getLogs" }),
    deleteLogs: () => bg({ type: "deleteLogs" }),
  };

  function renderLogs($list, items) {
    $list.empty();
    const last = (items || []).slice(-20).reverse();
    last.forEach((x) => {
      const $li = $("<li></li>");
      const $title = $("<div></div>").css("wordBreak", "break-all");
      const $badge = $("<span></span>")
        .addClass("badge")
        .addClass(x.event === "mockResponse" ? "event-mock" : x.event === "modifyResponse" ? "event-mod" : "event-pass")
        .text(x.event);
      const $method = $("<b></b>").text((x.method || "GET") + " ");
      const $url = $("<span></span>").text(x.url || "");

      $title.append($badge).append($method).append($url);

      const $meta = $("<div></div>")
        .addClass("meta")
        .text(`${fmtTime(x.time)} ${x.ruleId ? "规则#" + x.ruleId : ""} tab:${x.tabId ?? "-"} frame:${x.frameId ?? "-"}`);

      $li.append($title).append($meta);
      $list.append($li);
    });
  }

  async function loadAndRender($enabled, $ruleCountInfo, $logList) {
    const [st, logsResp] = await Promise.all([api.getState(), api.getLogs()]);
    if (st?.ok) {
      $enabled.prop("checked", !!st.data.enabled);
      const cnt = Array.isArray(st.data.rules) ? st.data.rules.length : 0;
      $ruleCountInfo.text(`规则: ${cnt}`);
    }
    renderLogs($logList, logsResp?.ok ? logsResp.data : []);
  }

  $(function () {
    const $enabled = $("#enabledSwitch");
    const $openOptions = $("#openOptions");
    const $refreshLogs = $("#refreshLogs");
    const $deleteLogs = $("#deleteLogs");
    const $logList = $("#logList");
    const $ruleCountInfo = $("#ruleCountInfo");

    $enabled.on("change", async function () {
      await api.setEnabled($enabled.prop("checked"));
      await loadAndRender($enabled, $ruleCountInfo, $logList);
    });

    $openOptions.on("click", function () {
      if (chrome.runtime.openOptionsPage) {
        chrome.runtime.openOptionsPage();
      } else {
        window.open("options.html", "_blank");
      }
    });

    $refreshLogs.on("click", function () {
      loadAndRender($enabled, $ruleCountInfo, $logList);
    });
    $deleteLogs.on("click", async function () {
      await api.deleteLogs();
      await loadAndRender($enabled, $ruleCountInfo, $logList);
    });

    loadAndRender($enabled, $ruleCountInfo, $logList);
  });
})();